package com.xysq.adapter;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.rockcent.action.AppAction;
import com.rockcent.action.CallbackListener;
import com.rockcent.model.CustCouponOrderBO;
import com.rockcent.model.constant.OrderState;
import com.umeng.analytics.MobclickAgent;
import com.xysq.activity.TipsActivity;
import com.xysq.activity.EvaluateActivity;
import com.xysq.fragment.ChangePriceDialogFragment;
import com.xysq.fragment.OrderListFragment;
import com.xysq.lemon.R;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.CircleImageView;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 描述信息
 *
 * @author keegan
 * @date 15/8/10
 */
public class OrderListAdapter extends BaseDataAdapter<CustCouponOrderBO> {

    AppAction appAction;
    int page;
    int type;
    Activity activity;
    OrderListFragment fragment;

    BaseAnimatorSet bas_in = new FlipVerticalSwingEnter();
    BaseAnimatorSet bas_out = new FadeExit();

    public OrderListAdapter(OrderListFragment fragment, FragmentActivity context, AppAction appAction, int page, int type) {
        super(context);
        this.fragment = fragment;
        activity = context;
        this.appAction = appAction;
        this.page = page;
        this.type = type;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_list_order, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final CustCouponOrderBO orderBO = itemList.get(position);
        String name = UseUtil.selectName(orderBO.getCustomerName(), orderBO.getPhone());
        holder.userNameTxt.setText(name);
        holder.userSchoolTxt.setText(orderBO.getSchoolName());
        holder.userPhoneTxt.setText(orderBO.getPhone());
        holder.goodsTitleTxt.setText(orderBO.getCouponName());
        holder.goodsNumberTxt.setText("数量：" + orderBO.getCount());
        holder.goodsPriceTxt.setText("￥" + UseUtil.handlePrice(orderBO.getPreferentialPrice()));
        if (TextUtils.isEmpty(orderBO.getHeadUrl()) || orderBO.getHeadUrl().equals("null")) {
            holder.photoImg.setImageResource(R.drawable.def_img_head);
        } else {
            if (orderBO.getHeadUrl().startsWith("http://")) {
                imageLoader.displayImage(orderBO.getHeadUrl(), holder.photoImg);
            } else {
                imageLoader.displayImage(PropertiesUtil.getImageServer() + orderBO.getHeadUrl(), holder.photoImg);
            }
        }

        holder.photoImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, TipsActivity.class);
                intent.putExtra(TipsActivity.COUPONMODEL_ID, orderBO.getCouponId());
                context.startActivity(intent);
            }
        });
        holder.userInfoLlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, TipsActivity.class);
                intent.putExtra(TipsActivity.COUPONMODEL_ID, orderBO.getCouponId());
                context.startActivity(intent);
            }
        });

        holder.phoneIbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + orderBO.getPhone()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);*/
                Uri smsToUri = Uri.parse("smsto:"+orderBO.getPhone());
                Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
                context.startActivity(intent);
            }
        });

        if (page == OrderListFragment.PAGE_RECEIVE) {
            if (type == 0) {
                holder.btnsLlayout.setVisibility(View.VISIBLE);
                holder.middleBtn.setText(context.getResources().getString(R.string.btn_handle_price));
                holder.middleBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MobclickAgent.onEvent(context, "1026");
                        ChangePriceDialogFragment dialogFragment = ChangePriceDialogFragment.newInstance((FragmentActivity) activity, orderBO);
                        dialogFragment.show(((FragmentActivity) activity).getSupportFragmentManager(), "ChangePriceDialogFragment");
                    }
                });
                holder.rightBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder(orderBO);
                    }
                });
            } else {
                holder.btnsLlayout.setVisibility(View.GONE);
            }
        } else {
            if (type == 2) {
                holder.btnsLlayout.setVisibility(View.GONE);
            } else {
                holder.btnsLlayout.setVisibility(View.VISIBLE);
                if (type == 1) {
                    holder.middleBtn.setEnabled(false);
                    holder.middleBtn.setText("");

                    if (orderBO.getOrderState() == OrderState.EVALUATED) {
                        holder.rightBtn.setText("已评价");
                        holder.rightBtn.setTextColor(context.getResources().getColor(R.color.text_gray));
                        holder.rightBtn.setEnabled(false);
                    } else {
//                        Log.e("ns", "进入了未评价");
                        holder.rightBtn.setText("未评价");

                        holder.rightBtn.setEnabled(true);
                        holder.rightBtn.setTextColor(context.getResources().getColor(R.color.text_normal));
                        holder.rightBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MobclickAgent.onEvent(context, "1030");
                                Intent intent = new Intent(context, EvaluateActivity.class);
                                intent.putExtra("couponModelId", orderBO.getCouponId());
                                intent.putExtra("orderId", String.valueOf(orderBO.getOrderId()));
                                context.startActivity(intent);
                            }
                        });
                    }
                } else {
                    holder.middleBtn.setEnabled(true);
                    holder.middleBtn.setText(context.getResources().getString(R.string.btn_confirm_pay));
                    holder.middleBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            confirm2Pay(orderBO);
                        }
                    });

                    holder.rightBtn.setText(context.getResources().getString(R.string.txt_remove_order));
                    holder.rightBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cancelOrder(orderBO);
                        }
                    });
                }
            }
        }

        return convertView;
    }

    class ViewHolder {
        @InjectView(R.id.llayout_user_info)
        LinearLayout userInfoLlayout;
        @InjectView(R.id.img_photo)
        CircleImageView photoImg;
        @InjectView(R.id.txt_user_name)
        TextView userNameTxt;
        @InjectView(R.id.txt_user_school)
        TextView userSchoolTxt;
        @InjectView(R.id.txt_user_phone)
        TextView userPhoneTxt;
        @InjectView(R.id.ibtn_phone)
        ImageButton phoneIbtn;
        @InjectView(R.id.txt_goods_title)
        TextView goodsTitleTxt;
        @InjectView(R.id.txt_goods_number)
        TextView goodsNumberTxt;
        @InjectView(R.id.txt_goods_price)
        TextView goodsPriceTxt;
        @InjectView(R.id.llayout_btns)
        LinearLayout btnsLlayout;
        @InjectView(R.id.btn_left)
        Button leftBtn;
        @InjectView(R.id.btn_middle)
        Button middleBtn;
        @InjectView(R.id.btn_right)
        Button rightBtn;

        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private void confirm2Pay(final CustCouponOrderBO orderBO) {
        MobclickAgent.onEvent(context, "1028");
        confirmBuyDialog(orderBO);
    }

    private void confirmBuyDialog(final CustCouponOrderBO orderBO) {
        final NormalDialog dialog = new NormalDialog(context);
        dialog.content("立马打赏到对方账户？")
                .title(context.getResources().getString(R.string.btn_confirm_pay) + "？")
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
            @Override
            public void onBtnLeftClick() {
                appAction.confirmOrder(orderBO.getOrderId(), new CallbackListener<Boolean>() {
                    @Override
                    public void onSuccess(Boolean data) {
                        if (data) {
                            ToastUtil.showShort(context, "付款成功");
                            fragment.reloadData();
                        } else {
                            ToastUtil.showShort(context, "付款失败");
                        }
                        dialog.dismiss();
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        ToastUtil.showShort(context, message);
                        dialog.dismiss();
                    }
                });
            }
        });

        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {
            @Override
            public void onBtnRightClick() {
                dialog.dismiss();
            }
        });
    }

    private void cancelOrder(final CustCouponOrderBO orderBO) {
        String message = "";
        if (page == OrderListFragment.PAGE_RECEIVE) {
            MobclickAgent.onEvent(context, "1027");
            message = "太任性了，给钱也不要！";
        }
        if (page == OrderListFragment.PAGE_ORDER) {
            MobclickAgent.onEvent(context, "1029");
            message = "跳票了，寡人不赏了";
        }
        confirmRemoveDialog(orderBO, message);
    }

    private void confirmRemoveDialog(final CustCouponOrderBO orderBO, String message) {
        final NormalDialog dialog = new NormalDialog(context);
        dialog.content(message)
                .title("给钱也不要了？")
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
            @Override
            public void onBtnLeftClick() {
                        appAction.cancelOrder(orderBO.getOrderId(), UserInfoKeeper.readCustomerId(context), new CallbackListener<Boolean>() {
                            @Override
                            public void onSuccess(Boolean data) {
                                if (data) {
                                    ToastUtil.showShort(context, "取消订单成功");
                                    fragment.reloadData();
                                } else {
                                    ToastUtil.showShort(context, "取消订单失败");
                                }
                                dialog.dismiss();
                            }

                            @Override
                            public void onFailure(String errorCode, String message) {
                                ToastUtil.showShort(context, message);
                                dialog.dismiss();
                            }
                        });
            }
        });

        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {
            @Override
            public void onBtnRightClick() {
                dialog.dismiss();
            }
        });
    }
}

